package xhhx.manager;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import xhhx.netty.ServerHandler;
import xhhx.network.GoogleProtobufDecode;
import xhhx.network.GoogleProtobufEncode;

public class NettyManager {
    final static int PORT = 10111;                          //端口
    final static int MAX_FRAME_BYTES_LENGTH = 1024 * 1024;      //最大比特长度
    final static int LENGTH_FIELD = 2;                     // 消息内容长度16位

    private static final EventLoopGroup bossGroup = new NioEventLoopGroup();
    private static final EventLoopGroup workerGroup = new NioEventLoopGroup();

    public static void Run() {
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128) // 服务器可连接队列大小
                    .option(ChannelOption.SO_REUSEADDR, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) {
                            ChannelPipeline p = ch.pipeline()
                                    .addLast(new LengthFieldBasedFrameDecoder(
                                            MAX_FRAME_BYTES_LENGTH, 0, LENGTH_FIELD, 0, LENGTH_FIELD, true))
                                    .addLast(new GoogleProtobufDecode())
                                    .addLast(new LengthFieldPrepender(LENGTH_FIELD, false))
                                    .addLast(new GoogleProtobufEncode())
                                    .addLast(new ServerHandler());
                        }
                    });

            ChannelFuture f = b.bind(PORT);
            System.out.println("=============================> Netty Start <=============================");
            f.sync();
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace(System.err);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            System.out.println("=============================> Netty Close <=============================");
        }
    }
}
